const pool = require('../config/db');
const { v4: uuidv4 } = require('uuid');

const Notification = {
    async create({ user_id, type, related_user_id, related_post_id, content }) {
        const notification_id = uuidv4();
        await pool.query(
            'INSERT INTO notifications (notification_id, user_id, type, related_user_id, related_post_id, content) VALUES (?, ?, ?, ?, ?, ?)',
            [notification_id, user_id, type, related_user_id, related_post_id, content]
        );
        return { notification_id };
    },

    async findByUserId(user_id, limit = 20, offset = 0) {
        const [rows] = await pool.query(
            'SELECT n.*, u.username AS related_username FROM notifications n LEFT JOIN users u ON n.related_user_id = u.user_id WHERE n.user_id = ? ORDER BY n.created_at DESC LIMIT ? OFFSET ?',
            [user_id, limit, offset]
        );
        return rows;
    },

    async markAsRead(notification_id) {
        await pool.query('UPDATE notifications SET is_read = TRUE WHERE notification_id = ?', [notification_id]);
    }
};

module.exports = Notification;